﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Config;
using AMM.Business.Project;
using AMM.Business.Store;
using AMM.CustomClassLibrary;
using AMM.CustomWinComponents.Validator;
using AMM.Model;
using AMM.Model.Project;
using AMM.Model.Store;

namespace AMM.UserControls {
    public partial class ProcurementOrderEditControl : BaseEditControl {

        private FlexBindingSource<ProcurementOrder> _fbs;
        private QuotationProcessor _quotationProcessor;
        private List<ProcurementOrderDetail> _podList;

        public override object BaseEditModel {
            get {
                this._fbs.CurrentItem.ProcurementOrderDetails = this.dgvMaterialEdit.GetDataSourceEx<ProcurementOrderDetail>();
                return this._fbs.CurrentItem;
            }
            set {
                if (this._fbs == null) { this._fbs = new FlexBindingSource<ProcurementOrder>(); }
                this._fbs.CurrentItem = (ProcurementOrder)value;
            }
        }

        public ProcurementOrderEditControl() {
            this.InitializeComponent();
        }

        private void BindVendor() {
            VendorSearchModel searchModel = new VendorSearchModel() { IsEnabled = true };
            VendorProcessor vendorProcessor = new VendorProcessor(int.MaxValue);
            List<VendorViewModel> vendorList = vendorProcessor.FetchVendorViewModelList(searchModel);

            this.ddlVendor.DisplayMemberEx = "Code";
            this.ddlVendor.ValueMemberEx = "Key";
            this.ddlVendor.HeightEx = 300;
            this.ddlVendor.WidthEx = 400;
            this.ddlVendor.PageSizeEx = 20;
            this.ddlVendor.DataBind(new VendorViewModel(), x => new { x.Code, x.Name, x.Address }, vendorList);
        }

        private void BindMaterial(int vendorId) {
            MaterialProcessor materialProcessor = new MaterialProcessor(int.MaxValue);
            List<MaterialViewModel> materialList = materialProcessor.FetchMaterialViewModelListByVendorId(vendorId);

            this.Material.DisplayMemberEx = "Code";
            this.Material.ValueMemberEx = "Key";
            this.Material.HeightEx = 300;
            this.Material.WidthEx = 400;
            this.Material.PageSizeEx = 20;
            this.Material.DataBind(new MaterialViewModel(), x => new { x.MaterialType, x.Code, x.Name, x.Remarks }, materialList);
        }

        private void BindSource() {
            this.Source.DataSource = new BasicsProcessor().FetchEnabledBasicsByType(BasicsType.ProcurementSourceType);
            this.Source.DisplayMember = "Name";
            this.Source.ValueMember = "BasicsId";
        }

        private void CreateFormBindings() {
            this._fbs.CreateBinding(this.ddlVendor, x => x.SelectedValueEx, y => y.VendorId);
            this._fbs.CreateBinding(this.tbCode, x => x.Text, y => y.Code, DataSourceUpdateMode.OnPropertyChanged);
        }

        private void BindValidation() {
            this.ValidatorForEdit.SetType(this.ddlVendor, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.ddlVendor, this.RequiredMessage);
        }

        private void BindDataGridView() {
            this.dgvMaterialEdit.DataSourceEx = this._podList;
        }

        private void ProcurementEditControl_Load(object sender, EventArgs e) {
            if (this._fbs == null) { this._fbs = new FlexBindingSource<ProcurementOrder>(); }
            this._quotationProcessor = new QuotationProcessor();
            this._podList = this._fbs.CurrentItem.ProcurementOrderDetails.ToList();

            this.BindMaterial(this._fbs.CurrentItem.VendorId);
            this.BindSource();
            this.BindVendor();
            this.BindDataGridView();
            this.CreateFormBindings();
            this.BindValidation();

            this.ddlVendor.Enabled = false;
            if (this._fbs.CurrentItem.ClassStatus == ClassStatus.Added) {
                string autoCode = CommonHelper.GenerateAutoCode("R");
                int maxNumber = new ProcurementOrderProcessor().GetTheMaxFlowNumber(autoCode);
                this._fbs.CurrentItem.Code = CommonHelper.GendrateSpecificCode(autoCode, maxNumber);
                this.ddlVendor.Enabled = true;
            }
        }

        private void ddlVendor_ValueChanged(object sender, EventArgs e) {
            this.BindMaterial(Convert.ToInt32(this.ddlVendor.SelectedValueEx));
        }

        private void dgvMaterialEdit_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
            if (e.RowIndex == -1) { return; }
            int vendorId = Convert.ToInt32(this.ddlVendor.SelectedValueEx);
            ProcurementOrderDetail currentPOD = (ProcurementOrderDetail)this.dgvMaterialEdit.Rows[e.RowIndex].DataBoundItem;
            Quotation quotation = this._quotationProcessor.FetchQuotationByVendorIdAndMaterialId(vendorId, currentPOD.MaterialId);
            if (quotation == null) {
                this.ShowError("未找到对应的报价单，或者是报价单未通过审核");
                return;
            }
            currentPOD.Price = quotation.IsMultiple
                ? currentPOD.Quantity > quotation.PriceThresholdValue ? quotation.PriceGreaterThan : quotation.Price
                : quotation.Price;
            currentPOD.Total = currentPOD.Quantity * currentPOD.Price;
            currentPOD.DeliveryDate = DateTime.Now.AddDays(quotation.PreProcurementCycle + quotation.ProcurementCycle);
            this._podList[e.RowIndex] = currentPOD;
            this.BindDataGridView();
        }
    }
}
